Showing posts with label Office 365. Show all posts
Showing posts with label Office 365. Show all posts

Sunday, June 5, 2016

Getting the files modified by a specified user

If you have any requirement to find out the files which has been modified by a specific user in sharepoint online.

Then here is the powershell script which will serve the purpose.

param
(
    [Parameter(Mandatory=$true)]
    [string]$SPSite,

    [Parameter(Mandatory=$true)]
    [string]$LoginName
)

function GetWebFiles($ctx, $web, $userId)

    Write-Host
    write-host "SITE: $($web.Url)"

    # Create a new custom object to hold our result.
    $siteObject = new-object PSObject

    # Add our data to $contactObject as attributes using the add-member commandlet
    $siteObject | add-member -membertype NoteProperty -name "Site URL" -Value $($web.Url)

    # Save the current $contactObject by appending it to $resultsArray ( += means append a new element to ‘me’)
    $resultsarray += $siteObject
    
    $strQuery = "<View Scope='RecursiveAll'><Query><Where><And>
                <Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>0</Value></Eq>
                <Or><Eq><FieldRef ID='Author' LookupId='True' /><Value Type='Lookup'>$($user.Id)</Value></Eq>
                <Eq><FieldRef ID='Editor' LookupId='True' /><Value Type='Lookup'>$($user.Id)</Value></Eq></Or>
                </And></Where></Query></View>"                  
     
    $lists = $web.Lists
        
    $ctx.Load($lists)
    $ctx.ExecuteQuery()

    foreach ($l in $lists)
    {       
        if ($l.BaseType.ToString() -eq "DocumentLibrary")
        {
            $camlQuery = new-object Microsoft.SharePoint.Client.CamlQuery
            $camlQuery.ViewXml = $strQuery

            $items = $l.GetItems($camlQuery)

            $ctx.Load($items)
            $ctx.ExecuteQuery()
       
            if ($items.Count -gt 0)
            {
                foreach ($item in $items)
                {
                    Write-Host "$($SPSite)$($item["FileRef"])" #"$($web.Url)$($item["FileRef"])"

                    # Create a new custom object to hold our result.
                    $siteObject = new-object PSObject

                    # Add our data to $contactObject as attributes using the add-member commandlet
                    $siteObject | add-member -membertype NoteProperty -name "Site URL" -Value "$($web.Url)$($item["FileRef"])"

                    # Save the current $contactObject by appending it to $resultsArray ( += means append a new element to ‘me’)
                    $resultsarray += $siteObject
                }
            }
        }       
    }
   
    $subWebs = $web.Webs

    $ctx.Load($subWebs)
    $ctx.ExecuteQuery()

    foreach ($subWeb in $subWebs)
    {
        GetWebFiles $ctx $subWeb $userId
    }
}

$username = Read-Host -Prompt "Enter Username"
$password = Read-Host -Prompt "Enter Password" -AsSecureString

$scriptPath = Split-Path $MyInvocation.MyCommand.Path

Add-Type -Path "$($scriptPath)\Microsoft.SharePoint.Client.dll"
Add-Type -Path "$($scriptPath)\Microsoft.SharePoint.Client.Runtime.dll"

# Declare an array to collect our result objects
$resultsarray =@()

try
{
    $teamSites = import-csv “$($scriptPath)\O365DTeamSites.csv”

    ForEach ($item in $teamSites)
    {
        $siteUrl = $item.(“Site URL”)

        #Write-Output “Site URL: $siteUrl”

        try
        {
            $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
   
            $creds = New-Object System.Net.NetworkCredential($username, $password)
            $ctx.Credentials = $creds;
                      
            $user = $ctx.Web.SiteUsers.GetByLoginName($LoginName)
                            
            $rootWeb = $ctx.Site.RootWeb  

            $ctx.Load($rootWeb)
            $ctx.Load($user)
            $ctx.ExecuteQuery()

            GetWebFiles $ctx $rootWeb $user.Id       
        }
        catch [Exception]
        {
            if($($_.Exception.Message) -ne "User cannot be found.")
            {
                write-host "Error checking site: $($siteUrl) -> $($_.Exception.Message)"
            }
            continue;
        }
    }

    $resultsarray| Export-csv $($scriptPath)\UserSites.csv -notypeinformation
}
catch [Exception]
{
    write-host "Error -> $($_.Exception.Message)"
    continue;
}


Happy Coding!!!

Retrieve My sites list in SharePoint online

When i was working on branidng for my sites, then i should get the list of my sites so that i can apply the custom branding to all the my sites.
So, in order to get the list of my sites, i have written the below code.

private static void GetMySites()
        {
            string siteUrl = "<root my site url>";
            string userName = "<Enter tenant admin user name>";
            string password = "<Enter tenant admin password>";

            SecureString securePassword = new SecureString();
            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }

            using (ClientContext clientContext = new ClientContext(siteUrl))
            {
                clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);

                Web web = clientContext.Web;
                clientContext.Load(web);
                clientContext.ExecuteQuery();

                List<SiteEntity> mysites = web.MySiteSearch();

                Console.WriteLine("My sites count: " + mysites.Count);

                string filePath = "D:\\GetMySites\MySites.txt";
                if (!System.IO.File.Exists(filePath))
                {
                    System.IO.File.Create(filePath).Close();
                }

                StringBuilder sbSites = new StringBuilder();
                using (System.IO.TextWriter writer = System.IO.File.CreateText(filePath))
                {
                    foreach (SiteEntity site in mysites)
                    {
                        sbSites = sbSites.Append(site.Url + ";");
                    }
                    writer.WriteLine(sbSites);
                }
            }
        }


Hope this code helps you to get the list of my sites in a text file.

Happy coding :)